package br.com.roteador.localizacao;

import java.util.Date;
import java.util.List;

import javax.enterprise.event.Observes;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import br.com.roteador.persistence.AbstractDAO;

@Named("localizacaoDAO")
public class LocalizacaoDAO extends AbstractDAO {

	public LocalizacaoDAO (EntityManager manager){
		this.manager = manager;
	}
	
	public void observaLocalizacao(@Observes Localizacao localizacao){
		localizacao.setDataHora(new Date());
		save(localizacao);
	}

	public LocalizacaoDAO (){}
	
	private static final long serialVersionUID = -196738644541630320L;

	public void recuperaUltimaLocalizacao() {
		recuperaTodos(Localizacao.class);
	}
	
	public List<Localizacao> recuperaPosicoes(String imei, Date dataInicio, Date dataFim){
		CriteriaBuilder qb = manager.getCriteriaBuilder();
		CriteriaQuery<Localizacao> cq = qb.createQuery(Localizacao.class);
		Root<Localizacao> tb = cq.from(Localizacao.class);
		Predicate eq3 = null;
		Predicate eq4 = null;
		Expression<Date> dtPrevIni = tb.get("dataHora");
		Expression<Date> dtPrevFim = tb.get("dataHora");
		eq3 = qb.greaterThanOrEqualTo(dtPrevFim, dataFim);
		eq4 = qb.lessThanOrEqualTo(dtPrevIni, dataInicio);
		cq.select(tb);
		cq.where(qb.and(eq3, eq4), qb.equal(tb.get("imei"), imei));
		return (List<Localizacao>) recuperaLista(montaQuery(cq));
	}
}
